<template>
  <div class="page-container">
    <div v-if="showLoading" class="loading-wrapper">
      <van-loading type="spinner">上传中...</van-loading>
    </div>
    <van-nav-bar
      title="上传验光报告"
      left-text=""
      right-text=""
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="upload-container">
      <van-uploader
        v-model="fileList"
        :before-read="beforeRead"
        :after-read="afterRead"
        :before-delete="beforeDelete"
        :max-count="UploadLimt"
        :multiple="true"
        :deletable="true"
      />
    </div>
    <div v-if="report_image.length !== 0" class="show-container">
      <div style="display: flex; flex-wrap: wrap">
        <van-image
          v-for="(item, index) in report_image"
          :key="index"
          class="show-img-item"
          :src="item"
          fit="cover"
          lazy-load
          @click="showImg(report_image, index)"
        >
          <template v-slot:loading>
            <van-loading type="spiner" size="20" />
          </template>
        </van-image>
      </div>
    </div>

    <van-goods-action>
      <van-goods-action-button type="info" text="确认上传" :loading="showLoading" @click="confirm" />
    </van-goods-action>
  </div>
</template>
<script>
import * as imageConversion from 'image-conversion'
import { upload } from '@/api/upload'
import { report as reportApi } from '@/api/user'
import {
  Button,
  Card,
  Tag,
  Toast,
  GoodsAction,
  GoodsActionButton,
  Uploader,
  Field,
  ImagePreview
} from 'vant'
export default {
  name: 'Home',
  components: {
    [Button.name]: Button,
    [Card.name]: Card,
    [Tag.name]: Tag,
    [Toast.name]: Toast,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionButton.name]: GoodsActionButton,
    [Uploader.name]: Uploader,
    [Field.name]: Field,
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  data() {
    return {
      showLoading: false,
      fileList: [],
      uploadData: [],
      recordImg: [],
      report_image: this.$route.query.report_image || []
    }
  },
  computed: {
    UploadLimt() {
      const RECORD_COUNT = this.recordImg.length
      const REMAIN_COUNT = 10 - RECORD_COUNT
      return REMAIN_COUNT
    }
  },
  created() {
    this.recordImg = this.$route.query.report_image.map((item, index) => {
      return {
        index: index,
        url: item
      }
    })
  },
  methods: {
    // 展示图片
    showImg(arr, index) {
      ImagePreview({
        images: arr,
        closeable: true,
        startPosition: index
      })
    },
    // 文件读取前的回调函数
    beforeRead(file) {
      this.showLoading = true
      if (file instanceof Array) {
        file.forEach((v) => {
          this.checkFile(v)
        })
      } else {
        this.checkFile(file)
      }
      return true
    },
    // 读取文件回调前检查+压缩
    checkFile(file) {
      console.log(file, '检查')
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      if (!isJpgOrPng) {
        Toast.fail('上传图片只能是JPG或PNG格式!')
        return false
      }
    },
    // 成功读取文件回调
    afterRead(file, detail) {
      console.log(file, '成功读取文件回调')
      if (file instanceof Array) {
        file.map((v) => {
          this.uploadImg(v, detail)
        })
      } else {
        this.uploadImg(file, detail)
      }
    },
    // 将图片上传至服务器
    async uploadImg(file, detail) {
      console.log(file, detail, '上传')
      // 大于2M压缩
      const isLt2M = file.file.size / (1024 * 1024).toFixed(2) > 2
      if (isLt2M) {
        await imageConversion
          .compressAccurately(file.file, 1536)
          .then((res) => {
            file.file = res
          })
      }
      const formData = new FormData()
      formData.append('image', file.file)
      await upload(formData).then((res) => {
        if (res.error.code === 0) {
          this.showLoading = false
          this.uploadData.push({ url: res.data.url, index: detail.index }) // 用detail.index其实不对，多选的时候，index是同一个，这样删除的时候就对应不上，不过用下标删除也行
        }
      })
    },
    // 文件删除前的回调函数
    beforeDelete(file, detail) {
      console.log(file, detail, '删除')
      // detail.index每个文件的下标
      this.uploadData.splice(detail.index, 1)
      return true
    },
    // 确认上传
    confirm() {
      if (this.uploadData.length === 0) {
        Toast.fail('请至少上传一张图片')
        return false
      }
      this.recordImg.forEach((item) => {
        if (item.url.indexOf('https') !== -1) {
          const arr = item.url.split('/')
          const tempArr = arr.slice(arr.length - 2, arr.length)
          const string = tempArr.join('/')
          item.url = string
        }
      })
      const record = this.recordImg.map((item) => item.url)
      const upload = this.uploadData.map((item) => item.url)
      const report = [...record, ...upload]
      // const report = []
      console.log(
        this.recordImg,
        record,
        this.uploadData,
        upload,
        report,
        '确认上传'
      )
      reportApi({ report }).then((res) => {
        if (res.error.code === 0) {
          Toast('上传成功')
          this.$router.push({ name: 'personal' })
        }
      })
    },
    // 返回
    onClickLeft() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.loading-wrapper {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;

  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  justify-content: center;
}
.page-container {
  height: 100vh;
  padding-bottom: 60px;
  box-sizing: border-box;
  overflow: auto;
}
.van-goods-action {
  width: 100%;
  max-width: 540px;
  margin: 0 auto;
}
.upload-container,
.show-container {
  margin-top: 10px;
  padding: 10px;
  background-color: #ffffff;
  font-size: 14px;
}
.show-img-item {
  margin: 0 5px 5px 0;
  width: 80px;
  height: 80px;
}
</style>
